"""
预订模型
"""
from sqlalchemy import Column, Integer, String, DateTime, DECIMAL, ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime
from extension import db


class Reservation(db.Model):
    """预订表"""
    __tablename__ = 'reservations'
    id = Column(Integer, primary_key=True)
    reservation_number = Column(String(20), unique=True, nullable=False, comment='预订编号')
    guest_id = Column(Integer, ForeignKey('guests.id'), nullable=False, comment='客户ID')
    room_id = Column(Integer, ForeignKey('rooms.id'), nullable=False, comment='房间ID')
    check_in = Column(DateTime, nullable=False, comment='入住日期时间')
    check_out = Column(DateTime, nullable=False, comment='退房日期时间')
    status = Column(Integer, default=1, comment='预订状态（1=待确认，2=已确认，3=已入住，4=已取消）')
    total_price = Column(DECIMAL(10, 2), default=0.0, comment='总价')
    deposit = Column(DECIMAL(10, 2), default=0.0, comment='押金')
    created_at = Column(DateTime, default=datetime.utcnow, comment='创建时间')
    updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, comment='更新时间')

    # 定义关系
    guest = relationship('Guest', back_populates='reservations', lazy=True)
    room = relationship('Room', back_populates='reservations', lazy=True)
    
    # 状态映射
    STATUS_PENDING = 1  # 待确认
    STATUS_CONFIRMED = 2  # 已确认
    STATUS_CHECKED_IN = 3  # 已入住
    STATUS_CANCELLED = 4  # 已取消
    
    STATUS_MAP = {
        STATUS_PENDING: '待确认',
        STATUS_CONFIRMED: '已确认',
        STATUS_CHECKED_IN: '已入住',
        STATUS_CANCELLED: '已取消'
    }
    
    def to_dict(self, include_relations=True):
        """转换为字典"""
        result = {
            'id': self.id,
            'reservation_number': self.reservation_number,
            'guest_id': self.guest_id,
            'room_id': self.room_id,
            'check_in': self.check_in.strftime('%Y-%m-%d') if self.check_in else None,
            'check_out': self.check_out.strftime('%Y-%m-%d') if self.check_out else None,
            'status': self.status,
            'status_text': self.STATUS_MAP.get(self.status, '未知状态'),
            'total_price': float(self.total_price) if self.total_price else 0,
            'deposit': float(self.deposit) if self.deposit else 0,
            'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else None,
            'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else None
        }
        
        # 如果包含关联对象，添加关联数据
        if include_relations:
            if self.guest:
                result['guest_name'] = self.guest.name
            if self.room:
                result['room_number'] = self.room.room_number
                if self.room.room_status:
                    result['room_status'] = self.room.room_status.name
        
        return result
    
    @classmethod
    def from_dict(cls, data):
        """从字典创建实例"""
        from datetime import datetime
        
        check_in = data.get('check_in')
        check_out = data.get('check_out')
        
        # 处理日期字符串
        if isinstance(check_in, str):
            check_in = datetime.strptime(check_in, '%Y-%m-%d')
        if isinstance(check_out, str):
            check_out = datetime.strptime(check_out, '%Y-%m-%d')
        
        return cls(
            reservation_number=data.get('reservation_number', ''),
            guest_id=data.get('guest_id'),
            room_id=data.get('room_id'),
            check_in=check_in,
            check_out=check_out,
            total_price=data.get('total_price', 0),
            deposit=data.get('deposit', 0),
            status=data.get('status', cls.STATUS_PENDING)
        )
    
    def update_from_dict(self, data):
        """从字典更新实例"""
        from datetime import datetime
        
        if 'guest_id' in data:
            self.guest_id = data['guest_id']
        if 'room_id' in data:
            self.room_id = data['room_id']
        if 'check_in' in data:
            check_in = data['check_in']
            if isinstance(check_in, str):
                check_in = datetime.strptime(check_in, '%Y-%m-%d')
            self.check_in = check_in
        if 'check_out' in data:
            check_out = data['check_out']
            if isinstance(check_out, str):
                check_out = datetime.strptime(check_out, '%Y-%m-%d')
            self.check_out = check_out
        if 'total_price' in data:
            self.total_price = data['total_price']
        if 'deposit' in data:
            self.deposit = data['deposit']
        if 'status' in data:
            self.status = data['status']
        return self

